import { pathOr } from 'ramda';

import errorCodesBuilder from '../../helpers/errorCodesBuilder';
import {
	VUL_LEVEL_MAP,
	SECURITY_EVENT_TYPE_MAP,
} from '../../../common/constants';
import { warnEventId } from '../../../common/warnId';
import request from './monitorTaskRequest';

const errorCodes = errorCodesBuilder();

// https://gitlab.intra.knownsec.com/websoc/console/iscanv/-/blob/develop/src/iscanv/ui/apps_basic/apps_glossary.py#L600
const categoryMap = {
	exp: '漏洞攻击',
	mode: '挂马传播',
	encode: '页面加密',
	anomalous: '可疑信息',
	safefilte: '潜在威胁',
	swf_check: 'FLASH漏洞攻击',
	cloud: '云端特征',
};

// https://gitlab.intra.knownsec.com/websoc/console/iscanv/-/blob/develop/src/iscanv/ui/apps_basic/apps_glossary.py#L620
const descriptionMap = {
	encode: {
		'encode-14': {
			'zh-cn': '使用ASCII 10进制加密编码',
			en: 'ASCII Hexadecimal encoding',
		},
		'encode-16': {
			'zh-cn': '使用HTMLSHIP加密编码',
			en: 'HTMLShip encryption',
		},
		'encode-11': {
			'zh-cn': 'MD5加密编码',
			en: 'MD5 encryption',
		},
		'encode-10': {
			'zh-cn': 'lion加密',
			en: 'lion encryption',
		},
		'encode-13': {
			'zh-cn': '使用JavaScript进行ASCII HEX加密编码',
			en: 'HEX encoding',
		},
		'encode-9': {
			'zh-cn': '使用US-ASCII加密',
			en: 'US-ASCII encoding',
		},
		'encode-8': {
			'zh-cn': '使用escape加密编码',
			en: 'escape encoding',
		},
		'encode-5': {
			'zh-cn': '使用VBS进行ASCII编码',
			en: 'ASCII encoding via VBS',
		},
		'encode-4': {
			'zh-cn': '使用packed压缩算法进行编码',
			en: 'packed and compressed encoding',
		},
		'encode-7': {
			'zh-cn': '使用ASCII 16进制编码数据',
			en: 'ASCII Decimal encoding',
		},
		'encode-6': {
			'zh-cn': '使用基于异或的算法进行编码',
			en: 'Xor encoding',
		},
		'encode-1': {
			'zh-cn': '使用document与unescape进行编码',
			en: 'document and unescape encoding',
		},
		'encode-2': {
			'zh-cn': '使用fromCharCode进行编码',
			en: 'JavaScript fromCharCode() Method encoding',
		},
	},
	anomalous: {
		'anomalous-24': {
			'zh-cn': '使用字符串结束符进行加密',
			en: 'obfuscation with “\0” string',
		},
		'anomalous-19': {
			'zh-cn': '恶意输出脚本标签',
			en: 'output script tag maliciously',
		},
		'anomalous-18': {
			'zh-cn': '加密编码浏览器对象',
			en: 'encode browser Object',
		},
		'anomalous-11': {
			'zh-cn': '怀疑使用shellcode(出现大量unicode编码)',
			en: 'suspicious to use shellcode (lots of unicode characters)',
		},
		'anomalous-10': {
			'zh-cn': '使用createobject创建ActiveX',
			en: 'create ActiveX with createobject',
		},
		'anomalous-13': {
			'zh-cn': '使用while恶意填充堆栈',
			en: 'filling stack maliciously with while loop',
		},
		'anomalous-12': {
			'zh-cn': '使用Array恶意填充堆栈',
			en: 'filling stack maliciously with Array',
		},
		'anomalous-15': {
			'zh-cn': '使用replace免杀',
			en: 'anti-virus invasion with replace',
		},
		'anomalous-14': {
			'zh-cn': '使用heapspray常用的填充数据',
			en: 'use the common-use data of heapspray',
		},
		'anomalous-17': {
			'zh-cn': '怀疑为挂马攻击分发母页',
			en: 'suspicious landing host that distributes malware',
		},
		'anomalous-16': {
			'zh-cn': '探测浏览器版本',
			en: 'probing the version of the browser',
		},
		'anomalous-20': {
			'zh-cn': '怀疑使用heapspray恶意填充内存',
			en: 'suspicious to allocate memory maliciously via heapspray',
		},
		'anomalous-21': {
			'zh-cn': '使用ani修改鼠标',
			en: 'modifying cursor via ANI',
		},
		'anomalous-22': {
			'zh-cn': '使用脚本嵌入脚本引用',
			en: 'use script with the scriput tag',
		},
		'anomalous-23': {
			'zh-cn': '使用unicode加密编码',
			en: 'unicode encoding',
		},
		'anomalous-9': {
			'zh-cn': '使用createElement创建ActiveX',
			en: 'create ActiveX with createElement',
		},
		'anomalous-8': {
			'zh-cn': '使用ActiveXObject创建ActiveX',
			en: 'create ActiveX with ActiveXObject',
		},
		'anomalous-5': {
			'zh-cn': '调用clsid对象',
			en: 'call “clsid” object',
		},
		'anomalous-4': {
			'zh-cn': '调用classid对象',
			en: 'call “classid” object',
		},
		'anomalous-7': {
			'zh-cn': '使用flashversion判断flash版本',
			en: 'identify the flash version with flashversion',
		},
		'anomalous-6': {
			'zh-cn': '使用getPlayerVersion判断flash版本',
			en: 'identify the flash version with getPlayerVersion',
		},
		'anomalous-1': {
			'zh-cn': 'heapspary模板',
			en: 'heapspray template',
		},
		'anomalous-3': {
			'zh-cn': '使用window.location进行重定向',
			en: 'redirection via windows.location',
		},
		'anomalous-2': {
			'zh-cn': 'shellcode常用数据',
			en: 'common data of shellcode',
		},
	},
	mode: {
		'mode-4': {
			'zh-cn': '使用JavaScript脚本加密并嵌入框架',
			en: 'Encoded with JavaScript and embedded into frame',
		},
		'mode-7': {
			'zh-cn': '资源引用目标地址被编码',
			en: 'encoded target URL in source reference',
		},
		'mode-1': {
			'zh-cn': '使用样式嵌入不可见的框架',
			en: 'embed hidden iframe via CSS',
		},
		'mode-2': {
			'zh-cn': '使用宽、高度属性嵌入不可见的框架',
			en: 'embed hidden iframe via width/height attribute',
		},
	},
	exp: {
		'exp-13': {
			'zh-cn': 'ppstream网络电视SetBkImage函数溢出漏洞',
			en:
				'PPStream PowerList.OCX SetBkImage ActiveX Control Buffer Overflow Vulnerability',
		},
		'exp-12': {
			'zh-cn': 'PPStream PowerPlayer.DLL ActiveX控件缓冲区溢出漏洞',
			en:
				'PPStream PowerPlayer.DLL ActiveX Control Buffer Overflow Vulnerability',
		},
		'exp-11': {
			'zh-cn':
				'Microsoft IE Speech API 4 COM对象实例化缓冲区溢出漏洞（MS07-033）',
			en:
				'Microsoft IE Speech API 4 COM Object ActiveX Control Memory Corruption Vulnerability (MS07-033)',
		},
		'exp-10': {
			'zh-cn':
				'Microsoft Internet Explorer HHCtrl ActiveX控件堆溢出漏洞(MS06-046)',
			en:
				'Microsoft Internet Explorer HHCtrl ActiveX Control Heap Overflow Vulnerability (MS06-046)',
		},
		'exp-17': {
			'zh-cn': '迅雷下载器DownURL2漏洞',
			en: 'Xunlei downloader (thunderbolt in English) DownURL2 Vulnerability',
		},
		'exp-16': {
			'zh-cn': '迅雷下载器location漏洞',
			en: 'Xunlei downloader (thunderbolt in English) Location Vulnerability ',
		},
		'exp-15': {
			'zh-cn': 'Realplayer播放器import漏洞',
			en: 'RealPlayer ierpplug.dll ActiveX real.import Vulnerability',
		},
		'exp-14': {
			'zh-cn': 'Realplayer播放器console漏洞',
			en:
				'RealPlayer ActiveX Control (rmoc3260.dll) Console Property Vulnerability',
		},
		'exp-19': {
			'zh-cn': 'Yahoo! Messenger Webcam 8.1(Ywcupl.dll)漏洞',
			en: 'Yahoo! Messenger Webcam 8.1(Ywcupl.dll) Vulnerability',
		},
		'exp-18': {
			'zh-cn': 'web迅雷下载任意文件漏洞',
			en: 'web thunder arbitrary file downloading Vulnerability',
		},
		'exp-3': {
			'zh-cn': 'IE7.0初始化内存远程执行代码漏洞(MS09-002)',
			en:
				'Internet Explorer7.0 Uninitialized Memory Corruption Vulnerability (MS09-002)',
		},
		'exp-2': {
			'zh-cn': '数据访问组件 (MDAC) 功能中的漏洞可能允许执行代码(MS06-014)',
			en:
				'Vulnerability in the Microsoft Data Access Components (MDAC) Function Could Allow Code Execution (MS06-014)',
		},
		'exp-1': {
			'zh-cn': '联众游戏大厅hgs_startNotify函数溢出漏洞',
			en: 'Ourgame GLWorld 2.x hgs_startNotify() ActiveX Buffer Overflow',
		},
		'exp-7': {
			'zh-cn': '超星阅读器loadpage函数远程溢出漏洞',
			en:
				'MSIE SSReader Ultra Star Reader ActiveX Control LoadPage() remote buffer overflow Vulnerability',
		},
		'exp-6': {
			'zh-cn': '超星register函数漏洞',
			en:
				'SSReader Ultra Star Reader ActiveX control register() buffer overflow',
		},
		'exp-5': {
			'zh-cn': 'Microsoft IE对象处理内存破坏漏洞(MS08-078)',
			en:
				'Microsoft Internet Explorer XML Handling Remote Code Execution Vulnerability (MS08-078)',
		},
		'exp-4': {
			'zh-cn': 'Office Access Snapshot Viewer漏洞',
			en:
				'Office Access Snapshot Viewer ActiveX Control Remote Code Execution Vulnerability ',
		},
		'exp-9': {
			'zh-cn': '联众游戏大厅ChatRoom函数溢出漏洞',
			en:
				'Ourgame GLChat.ocx ActiveX Control ChatRoom() Overflow Vulnerability',
		},
		'exp-8': {
			'zh-cn': '联众游戏大厅ConnectAndEnterRoom函数溢出漏洞',
			en:
				'Ourgame ConnectAndEnterRoom ActiveX Control Stack Overflow Vulnerability',
		},
		'exp-88': {
			'zh-cn': 'Mozilla Firefox 小于等于 1.04 compareTo() 远程代码执行漏洞',
			en:
				'Mozilla Firefox lt or = 1.04 compareTo() Remote Code Execution Exploit',
		},
		'exp-89': {
			'zh-cn': 'Mozilla/Netscape/Firefox浏览器域名远程溢出漏洞',
			en: 'Mozilla Browsers 0xAD (HOST:) Remote Heap Buffer Overrun Exploit',
		},
		'exp-84': {
			'zh-cn': 'Microsoft IE COM对象实例化daxctle.ocx堆破坏漏洞（MS06-067）',
			en: 'MS Internet Explorer COM Object Remote Heap Overflow Exploit',
		},
		'exp-85': {
			'zh-cn': 'Firefox 小于等于 1.5.0.4 Javascript navigator 对象代码执行漏洞',
			en: 'Firefox lt or = 1.5.0.4 Javascript navigator Object Code Execution ',
		},
		'exp-86': {
			'zh-cn':
				'Microsoft Internet Explorer CreateTextRange远程代码执行漏洞(MS06-013)',
			en: 'MS Internet Explorer (createTextRang) Download Shellcoded Exploit',
		},
		'exp-87': {
			'zh-cn': 'MS Windows Media Player 10 插件溢出漏洞(MS06-006)',
			en: 'MS Windows Media Player 10 Plugin Overflow Exploit (MS06-006)',
		},
		'exp-80': {
			'zh-cn': 'Mozilla Firefox 小于等于 2.0.0.1 (location.hostname) 跨域漏洞',
			en:
				'Mozilla Firefox lt or = 2.0.0.1 (location.hostname) Cross-Domain Vulnerability',
		},
		'exp-81': {
			'zh-cn': 'MS Internet Explorer 7 弹出窗口地址栏信息欺骗漏洞',
			en: 'MS Internet Explorer 7 Popup Address Bar Spoofing Weakness',
		},
		'exp-82': {
			'zh-cn': 'MS Internet Explorer WebViewFolderIcon setSlice() 溢出攻击',
			en: 'MS Internet Explorer WebViewFolderIcon setSlice() Exploit',
		},
		'exp-83': {
			'zh-cn': 'Microsoft IE畸形VML文档处理缓冲区溢出漏洞(MS06-055)',
			en: 'MS Internet Explorer (VML) Remote Buffer Overflow Exploit',
		},
		'exp-66': {
			'zh-cn': 'Office Viewer OCX 3.2 远程文件执行漏洞',
			en: 'Office Viewer OCX 3.2 Remote File Execution exploit',
		},
		'exp-67': {
			'zh-cn': 'Word Viewer OCX 3.2 远程文件执行漏洞',
			en: 'Word Viewer OCX 3.2 Remote File Execution exploit',
		},
		'exp-64': {
			'zh-cn': 'PowerPoint Viewer OCX 3.2 远程文件执行漏洞',
			en: 'PowerPoint Viewer OCX 3.2 Remote File Execution exploit',
		},
		'exp-65': {
			'zh-cn': 'Office Viewer OCX 3.2 远程文件执行漏洞',
			en: 'Office Viewer OCX 3.2 Remote File Execution exploit',
		},
		'exp-62': {
			'zh-cn': 'Excel Viewer OCX 3.2 远程文件执行漏洞',
			en: 'Excel Viewer OCX 3.2 Remote File Execution Exploit',
		},
		'exp-63': {
			'zh-cn': 'Word Viewer OCX 3.2 远程文件执行漏洞',
			en: 'Word Viewer OCX 3.2 Remote File Execution exploit',
		},
		'exp-60': {
			'zh-cn': 'Mozilla Firefox 3.5 (Font tags) 远程堆栈溢出漏洞 (osx)',
			en:
				'Mozilla Firefox 3.5 (Font tags) Remote Buffer Overflow Exploit (osx)',
		},
		'exp-61': {
			'zh-cn': 'Google Chrome 1.0.154.46 (ChromeHTML://)参数注入漏洞',
			en: 'Google Chrome 1.0.154.46 (ChromeHTML://) Parameter Injection PoC',
		},
		'exp-68': {
			'zh-cn': 'Microsoft XML Core Services DTD跨域信息泄露漏洞（MS08-069）',
			en: 'Microsoft XML Core Services DTD Cross-Domain Scripting (MS08-069)',
		},
		'exp-69': {
			'zh-cn': 'Opera 9.61 opera:historysearch 代码执行漏洞',
			en: 'Opera 9.61 opera:historysearch Code Execution Exploit',
		},
		'exp-99': {
			'zh-cn': 'MS Internet Explorer iframe标签溢出漏洞',
			en: 'MS Internet Explorer (IFRAME Tag) Buffer Overflow Exploit',
		},
		'exp-98': {
			'zh-cn': 'MS Internet Explorer 6.0 SP2 文件下载安全警告绕过漏洞',
			en: 'MS Internet Explorer 6.0 SP2 File Download Security Warning Bypass',
		},
		'exp-93': {
			'zh-cn': 'Mozilla Firefox 查看源代码脚本协议URL代码执行漏洞',
			en: 'Mozilla Firefox view-source:javascript url Code Execution Exploit',
		},
		'exp-92': {
			'zh-cn': 'Microsoft IE javaprxy.dll COM对象实例化堆溢出漏洞(MS05-037)',
			en: 'MS Internet Explorer (javaprxy.dll) COM Object Remote Exploit',
		},
		'exp-91': {
			'zh-cn': 'Mozilla Firefox 小于等于 1.0.4 (设置背景) 任意代码执行漏洞',
			en:
				'Mozilla Firefox lt or = 1.0.4 (Set As Wallpaper) Code Execution Exploit',
		},
		'exp-90': {
			'zh-cn':
				'Microsoft Internet Explorer COM对象实例化代码执行漏洞（MS05-038）',
			en:
				'MS Internet Explorer (blnmgr.dll) COM Object Remote Exploit (MS05-038)',
		},
		'exp-97': {
			'zh-cn': 'MS Internet Explorer (hhctrl.ocx) 远程代码执行漏洞',
			en: 'MS Internet Explorer Remote Code Execution with Parameters',
		},
		'exp-96': {
			'zh-cn': 'MS Internet Explorer DHTML 对象内存污染漏洞',
			en: 'MS Internet Explorer DHTML Object Memory Corruption Exploit',
		},
		'exp-95': {
			'zh-cn': 'Mozilla浏览器 x (Link)代码执行漏洞',
			en: 'Mozilla Browsers x (Link) Code Execution Exploit',
		},
		'exp-94': {
			'zh-cn': 'Mozilla Firefox Install方法远程任意代码执行漏洞',
			en:
				'Mozilla Firefox Install Method Remote Arbitrary Code Execution Exploit',
		},
		'exp-75': {
			'zh-cn': 'MS Internet Explorer 打印跨域执行脚本',
			en: 'MS Internet Explorer (Print Table of Links) Cross-Zone Scripting',
		},
		'exp-74': {
			'zh-cn': 'Google Chrome SaveAs函数Title标签栈溢出漏洞',
			en: 'Google Chrome Browser 0.2.149.27 (SaveAs) Remote BOF Exploit',
		},
		'exp-77': {
			'zh-cn':
				'IE6 / Provideo Camimage (ISSCamControl.dll 1.0.1.5) 远程溢出漏洞',
			en:
				'IE6 / Provideo Camimage (ISSCamControl.dll 1.0.1.5) Remote BoF Exploit',
		},
		'exp-76': {
			'zh-cn': 'Safari 3 for Windows Beta 远程代码执行漏洞',
			en: 'Safari 3 for Windows Beta Remote Command Execution',
		},
		'exp-71': {
			'zh-cn': 'MW6 DataMatrix ActiveX (DataMatrix.dll) 远程不安全方法漏洞',
			en: 'MW6 DataMatrix ActiveX (DataMatrix.dll) Insecure Method Exploit',
		},
		'exp-70': {
			'zh-cn': 'MW6 PDF417 ActiveX (MW6PDF417.dll) 远程不安全方法漏洞',
			en: 'MW6 PDF417 ActiveX (MW6PDF417.dll) Remote Insecure Method Exploit',
		},
		'exp-73': {
			'zh-cn': 'MW6 Aztec ActiveX (Aztec.dll) 远程方法不安全漏洞',
			en: 'MW6 Aztec ActiveX (Aztec.dll) Remote Insecure Method Exploit',
		},
		'exp-72': {
			'zh-cn': 'MW6 Barcode ActiveX (Barcode.dll)  远程方法不安全漏洞',
			en: 'MW6 Barcode ActiveX (Barcode.dll) Insecure Method Exploit',
		},
		'exp-79': {
			'zh-cn': 'MS Internet Explorer Recordset 内存重用漏洞(MS07-009)',
			en:
				'MS Internet Explorer Recordset Double Free Memory Exploit (MS07-009)',
		},
		'exp-78': {
			'zh-cn': 'IE 6 / Ademco, co., ltd. ATNBaseLoader100 模块远程溢出',
			en: 'IE 6 / Ademco, co., ltd. ATNBaseLoader100 Module Remote BoF Exploit',
		},
		'exp-40': {
			'zh-cn':
				'Microsoft Windows Media Encoder WMEX.DLL ActiveX控件缓冲区溢出漏洞（MS08-053）',
			en:
				'Microsoft Windows Media Encoder WMEX.DLL ActiveX Control Buffer Overrun Vulnerability（MS08-053）',
		},
		'exp-41': {
			'zh-cn': 'Microsoft DirectShow MPEG2TuneRequest组件栈溢出漏洞(MS09-032)',
			en:
				'Microsoft DirectShow MPEG2TuneRequest Stack Overflow Vulnerability (MS09-032) / Microsoft Video ActiveX Control (msvidctl.dll) Remote Code Execution Vulnerability ',
		},
		'exp-42': {
			'zh-cn': 'Firefox3.5(Font tags)漏洞',
			en: 'Firefox3.5 (Font tags)Heap Spray Vulnerability',
		},
		'exp-43': {
			'zh-cn': '暴风影音播放器OnBeforeVideoDownload函数溢出漏洞',
			en:
				"BaoFeng Storm ActiveX Control 'OnBeforeVideoDownload()' Buffer Overflow Vulnerability",
		},
		'exp-44': {
			'zh-cn': '联众游戏世界CreateChinagames函数溢出漏洞',
			en:
				'Chinagames iGame CGAgent ActiveX (CGAgent.dll) CreateChinagames() Function Overflow Vulnerability',
		},
		'exp-45': {
			'zh-cn': 'IE极光漏洞',
			en:
				"Internet Explorer 'srcElement()' Free Object Remote Code Execution (Aurora)Vulnerability (CVE-2010-0249)",
		},
		'exp-46': {
			'zh-cn': 'Microsoft IE畸形对象操作内存破坏漏洞(MS10-018)',
			en:
				'Microsoft Internet Explorer iepeers.dll use-after-free Object Memory Corruption Vulnerability',
		},
		'exp-47': {
			'zh-cn': 'Microsoft IE CSS标签解析远程代码执行漏洞',
			en:
				'Microsoft Internet Explorer CSS Tags Uninitialized Memory Remote Code Execution Vulnerability (MS10-018)',
		},
		'exp-48': {
			'zh-cn':
				'Firefox 3.6.8 - 3.6.11 交叉 document.write 与 appendChild 攻击 ',
			en:
				'Firefox 3.6.8 - 3.6.11 Interleaving document.write and appendChild Exploit',
		},
		'exp-49': {
			'zh-cn': 'Adobe Shockwave player rcsL 内存覆盖漏洞',
			en: 'Adobe Shockwave player rcsL chunk memory corruption 0day',
		},
		'exp-59': {
			'zh-cn': 'Mozilla Firefox 2.0.0.16 UTF-8 URL远程堆栈溢出漏洞',
			en: 'Mozilla Firefox 2.0.0.16 UTF-8 URL Remote Buffer Overflow Exploit',
		},
		'exp-58': {
			'zh-cn': 'WebKit XML信息泄露漏洞',
			en: 'WebKit XML External Entity Information Disclosure Vulnerability',
		},
		'exp-57': {
			'zh-cn': 'Adobe ShockWave Player SwDir.dll控件堆溢出漏洞',
			en:
				'Adobe Shockwave 11.5.1.601 Player Multiple Code Execution Vulnerability',
		},
		'exp-56': {
			'zh-cn': 'IE wshom.ocx ActiveX Control远程代码执行漏洞',
			en:
				'Microsoft Internet Explorer wshom.ocx ActiveX Control Remote Code Execution Vulnerability',
		},
		'exp-55': {
			'zh-cn': "Internet Explorer 'winhlp32.exe' 'MsgBox()'远程代码执行漏洞",
			en:
				"Internet Explorer 'winhlp32.exe' 'MsgBox()' Remote Code Execution Vulnerability",
		},
		'exp-54': {
			'zh-cn': 'Apple Safari 4.0.5 parent.close()代码执行漏洞',
			en:
				'Apple Safari 4.0.5 parent.close() (memory corruption) 0day Code Execution Exploit',
		},
		'exp-53': {
			'zh-cn':
				'Google Chrome 4.1.249.1059利用 Google URL (GURL)绕过同源策略漏洞',
			en: 'Google Chrome 4.1.249.1059 Cross Origin Bypass in Google URL (GURL)',
		},
		'exp-52': {
			'zh-cn': 'Microsoft Windows帮助和支持中心绕过白名单限制漏洞(MS10-042)',
			en:
				'Microsoft Windows Help And Support Center Trusted Document Whitelist Bypass Vulnerability (MS10-042)',
		},
		'exp-51': {
			'zh-cn': 'Image22 ActiveX v1.1.1堆栈溢出漏洞',
			en: 'Image22 ActiveX v1.1.1 Buffer Overflow Exploit',
		},
		'exp-50': {
			'zh-cn': 'Netscape Browser v9.0.0.6 点击劫持漏洞',
			en: 'Netscape Browser v9.0.0.6 Clickjacking Vulnerability',
		},
		'exp-28': {
			'zh-cn':
				'新浪DLoader Class ActiveX控件DonwloadAndInstall方式任意文件下载漏洞',
			en:
				"Sina DLoader Class ActiveX Control 'DonwloadAndInstall' Method Arbitrary File Download Vulnerability",
		},
		'exp-29': {
			'zh-cn': "SymantecWinFax Pro 'DCCFAXVW.DLL'堆缓冲区溢出漏洞",
			en:
				"Symantec WinFax Pro 'DCCFAXVW.DLL' Heap Buffer Overflow Vulnerability",
		},
		'exp-22': {
			'zh-cn':
				'Microsoft Windows媒体服务器mdsauth.dll控件远程代码执行漏洞（MS07-027）',
			en:
				'Microsoft Windows Media Server MDSAuth.DLL ActiveX Control Remote Code Execution Vulnerability (MS07-027)',
		},
		'exp-23': {
			'zh-cn': 'Microsoft IE WebViewFolderIcon远程整数溢出漏洞(MS06-057)',
			en:
				'Microsoft Internet Explorer WebViewFolderIcon ActiveX Control Integer Overflow Vulnerability (MS06-057)',
		},
		'exp-20': {
			'zh-cn': '暴风影音播放器rawparse溢出漏洞',
			en:
				'Baofeng StormPlayer “rawParse()” Methods Stack Buffer Overflow Vulnerability',
		},
		'exp-21': {
			'zh-cn': '百度搜霸下载执行任意文件漏洞',
			en:
				'BaiduBar obj.DloadDS ActiveX Control Download and Execute Arbitrary Code Vulnerability',
		},
		'exp-26': {
			'zh-cn': '快播QvodInsert.dll控件超长URL缓冲区溢出漏洞',
			en:
				'The QVOD Player ActiveX Control (QvodInsert.dll) Overlong URL Heap-based Buffer Overflow Vulnerability',
		},
		'exp-27': {
			'zh-cn': 'UUSEE网络电视下载执行任意文件漏洞',
			en:
				"UUSee UUUpgrade ActiveX Control 'Update' Method Arbitrary File Download Vulnerability",
		},
		'exp-24': {
			'zh-cn': 'Microsoft Windows矢量标记语言缓冲区溢出漏洞（MS07-004）',
			en:
				'Microsoft Windows Vector Markup Language (VML) Buffer Overrun Vulnerability(MS07-004)',
		},
		'exp-25': {
			'zh-cn': 'Microsoft Agent URI解析远程代码执行漏洞（MS07-020）',
			en:
				'Microsoft Agent URL Parsing Remote Code Execution Vulnerability (MS07-020)',
		},
		'exp-100': {
			'zh-cn': 'Microsoft Internet Explorer恶意快捷方式自动执行HTML漏洞',
			en: 'MS Internet Explorer Remote Application.Shell Exploit',
		},
		'exp-101': {
			'zh-cn':
				'Microsoft Internet Explorer NavigateAndFind()跨域策略漏洞（MS04-004）',
			en: 'MS Internet Explorer URL Injection in History List (MS04-004)',
		},
		'exp-102': {
			'zh-cn': 'Internet Explorer Object数据远程执行漏洞（MS03-032）',
			en: 'MS Internet Explorer Object Data Remote Exploit (M03-032)',
		},
		'exp-103': {
			'zh-cn':
				'Microsoft Internet Explorer对象类型属性缓冲区溢出漏洞（MS03-020）',
			en: 'MS Internet Explorer Object Tag Exploit (MS03-020)',
		},
		'exp-104': {
			'zh-cn': '迅雷PPLAYER.DLL_1_WORK ActiveX控件缓冲区溢出漏洞',
			en:
				'Xunlei Thunder PPLAYER.DLL_1_WORK ActiveX Control Buffer Overflow Vulnerability',
		},
		'exp-105': {
			'zh-cn': '联众世界GLIEDown2.dll Active控件多个缓冲区溢出漏洞',
			en:
				'Ourgame GLIEDown2.dll ActiveX Control Multiple Buffer Overflow Vulnerability',
		},
		'exp-106': {
			'zh-cn':
				"Microsoft Windows Media Player 'winmm.dll' MIDI文件解析远程代码执行漏洞(MS12-004)",
			en:
				"Microsoft Windows Media Player 'winmm.dll' MIDI file parsing remote code execution vulnerability",
		},
		'exp-39': {
			'zh-cn': 'IE CODEBASE漏洞',
			en:
				'Microsoft Internet Explorer CODEBASE Value Remote Code Execution Vulnerability',
		},
		'exp-38': {
			'zh-cn': 'Microsoft XML核心服务XMLHTTP控件内存破坏漏洞（MS06-071）',
			en:
				'Microsoft XML Core Services XMLHTTP Control Memory Corruption Remote Code Execution Vulnerability (MS06-071)',
		},
		'exp-31': {
			'zh-cn': 'McAfee Security Center McSubMgr.DLL ActiveX控件远程溢出漏洞',
			en:
				'McAfee Security Center McSubMgr.DLL ActiveX Control Remote Buffer Overflow Vulnerability',
		},
		'exp-30': {
			'zh-cn':
				'COWON America jetAudio JetFlExt.dll ActiveX控件远程命令执行漏洞',
			en:
				'COWON America jetAudio JetFlExt.dll ActiveX Control Insecure Method Remote Code Execution Vulnerability.',
		},
		'exp-33': {
			'zh-cn': 'Microsoft Office Web Components Spreadsheet漏洞',
			en:
				'Microsoft Office Web Components (Spreadsheet) ActiveX Control “msDataSourceObject()” method Memory Corruption Vulnerability (MS 09-043) ',
		},
		'exp-32': {
			'zh-cn': 'Opera浏览器toUpperCase()漏洞',
			en:
				'Opera app_iframe.src.toUpperCase() Remote Code Execution Vulnerability',
		},
		'exp-35': {
			'zh-cn': '千千静听med文件格式堆溢出',
			en:
				'TTPlayer libmodplug CSoundFile::ReadMed() Function Buffer Overflow Vulnerability',
		},
		'exp-34': {
			'zh-cn': '瑞星杀毒软件下载执行任意程序漏洞',
			en:
				'Rising Antivirus Online Scanner ActiveX Control Insecure Method Remote Code Execution',
		},
		'exp-37': {
			'zh-cn': 'Window media player SaveToFile()漏洞',
			en:
				'Window Media Player and Internet Explorer 6 SaveToFile() Vulnerability',
		},
		'exp-36': {
			'zh-cn': '新浪UC2006 SendChatRoomOpt对象堆栈溢出漏洞',
			en:
				'Sina UC2006 ActiveX Control SendChatRoomOpt() Method Buffer Overflow Vulnerability ',
		},
	},
};
const getAffectsUrl = (pathArr, target) => {
	const data = { affects: '', addition: { outURL: '' } };
	for (let index = pathArr.length - 1; index >= 0; index--) {
		const e = pathArr[index];
		if (e.startsWith(target)) {
			data.affects = e;
			data.addition.outURL =
				index === pathArr.length - 1 ? '' : pathArr[index + 1];
			break;
		}
	}
	return data;
};
const parserMap = {
	black_links: (data, target) =>
		Object.entries(data).map(([affects, detail]) => ({
			detail,
			addition: getAffectsUrl(detail.refer_path, target).addition,
			affects: getAffectsUrl(detail.refer_path, target).affects,
			id: warnEventId({
				affects,
				taskType: 'securityEvent',
				id: 'black_links',
			}),
			level: VUL_LEVEL_MAP['高'],
			title: SECURITY_EVENT_TYPE_MAP.black_links,
			category: 'black_links',
			detailText: `${affects} 发现暗链 ${detail.links.length} 个`,
		})),
	broken_links: (data, target) => {
		const pageMap = data.reduce((obj, x) => {
			const [link, page] = x.slice(-2);
			obj[page] = obj[page] || [];
			obj[page].push(link);
			obj[page].push(x[0]);
			return obj;
		}, {});
		return Object.entries(pageMap).map(([affects, links]) => {
			const _links = links;
			const linksEnd = _links.pop();
			return {
				id: warnEventId({
					affects,
					taskType: 'securityEvent',
					id: 'broken_links',
				}),
				addition: {
					outURL: linksEnd.startsWith(target) ? '' : linksEnd,
				},
				level: VUL_LEVEL_MAP['中'],
				title: SECURITY_EVENT_TYPE_MAP.broken_links,
				category: 'broken_links',
				affects,
				detailText: `${affects} 发现坏链 ${_links.length} 个`,
				detail: _links,
			};
		});
	},
	cryjack: (data, target) =>
		Object.entries(data).map(([affects, detail]) => ({
			addition: getAffectsUrl(detail.refer_path, target).addition,
			affects: getAffectsUrl(detail.refer_path, target).affects,
			id: warnEventId({ affects, taskType: 'securityEvent', id: 'cryjack' }),
			level: VUL_LEVEL_MAP['高'],
			title: SECURITY_EVENT_TYPE_MAP.cryjack,
			category: 'cryjack',
			detailText: `${affects} 发现 ${detail.results.length} 处恶意挖矿程序特征`,
			detail: detail.results,
		})),
	malscan: (data, target) =>
		Object.entries(data).map(([affects, info]) => {
			const detail = Object.keys(descriptionMap).reduce((arr, categoryKey) => {
				const section = pathOr({}, ['staticinfo', categoryKey], info);
				const vulList = Object.entries(section);
				if (vulList.length === 0) return arr;

				vulList.forEach(([url, vuls]) => {
					Object.keys(vuls).forEach(vulKey => {
						const description = pathOr(
							'',
							[categoryKey, vulKey, 'zh-cn'],
							descriptionMap
						);
						arr.push({
							description,
							url,
							category: categoryMap[categoryKey],
						});
					});
				});

				return arr;
			}, []);
			return {
				detail,
				addition: getAffectsUrl(info.refer_path, target).addition,
				affects: getAffectsUrl(info.refer_path, target).affects,
				id: warnEventId({
					affects,
					taskType: 'securityEvent',
					id: 'malscan',
				}),
				level: VUL_LEVEL_MAP['高'],
				title: '网页挂马',
				category: 'malscan',
				detailText: `${affects} 发现 ${detail.length} 处网页挂马特征`,
			};
		}),
};

export function resultParser({ plugins, target }) {
	const warnings = Object.entries(plugins).reduce((arr, [type, detail]) => {
		const parser = parserMap[type];
		if (!parser) return arr;
		return arr.concat(parser(detail, target));
	}, []);
	return { warnings, addition: { statistics: plugins.statistics } };
}

export default (config, server) =>
	async function securityEvent(job) {
		const api = config.api;

		const { target, collect } = job.data;

		const payload = {
			site: target,
			include_plugins: ['statistics'].concat(collect.plugins),
			foreign_link_plugins: ['statistics'].concat(collect.plugins),
		};
		if (collect.depth) {
			payload.depth = collect.depth;
		}
		if (collect.maxPage) {
			payload.max_page = collect.maxPage;
		}

		let result;
		try {
			result = await request({
				job,
				payload,
				api,
				checkInterval: config.checkInterval,
			});
		} catch (err) {
			const error = errorCodes['[06]安全事件监测任务创建失败'].from(err);
			server.log.error(
				{
					error,
					job,
					payload,
					api,
					checkInterval: config.checkInterval,
				},
				error.rawMessage
			);
			throw error;
		}

		if (!result?.plugins) {
			server.log.warn({ result, api, job: job.data }, '漏洞扫描结果为空');
		}
		return resultParser(result);
	};
